<?php /** @noinspection PhpComposerExtensionStubsInspection */

/**
 * Created by PhpStorm.
 * User: 35906
 * Date: 18.9.19
 * Time: 18:45
 */

class TuringApi
{
    public $sentText;
    public $postData;
    public $getData;
    public $reContent='';
    public $ch;

    static $singleObject = null;

    private function __construct()
    {

        $this->ch = curl_init('http://openapi.tuling123.com/openapi/api/v2');
        curl_setopt( $this->ch, CURLOPT_POST, 1);
        curl_setopt( $this->ch, CURLOPT_RETURNTRANSFER, 1);
    }

    static public function getObj(){
        if(self::$singleObject ==null){
            self::$singleObject = new TuringApi();
        }
        return self::$singleObject;
    }

    public function setPost($text,$username,$groupId='',$userIdName=''){
        $this->sentText = $text;
        $this->postData = [
            'perception' => [
                'inputText' => [
                    'text' => $text,
                ],
            ],
            'userInfo' => [
                'apiKey' => '77107ae29ea4476f8d2048f4af49e83c',
                'userId' => $username,
            ]
        ];
        if($groupId!=''){
            $this->postData['userInfo']['groupId']=$groupId;
        }
        if($userIdName!=''){
            $this->postData['userInfo']['userIdName']=$userIdName;
        }
    }

    public function sent(){

        curl_setopt($this->ch,CURLOPT_POSTFIELDS,json_encode($this->postData,JSON_UNESCAPED_UNICODE));
        $this->getData = json_decode(curl_exec($this->ch),true);
        $this->reContent = '';
        foreach ($this->getData['results']??[] as $result){
            foreach ($result['values'] as $value) {
                $this->reContent .= ' ' . $value . '';
            }
        }
        return $this->reContent;
    }
}
////
//$turing = new TuringApi();
//$turing->setPost('你好!','a6d9466881bfb6d6a4c43340b16d893b');
//$turing->sent();
//var_export($turing->getData);